// ------------------------------ 循环链表 --------------------------------------

class Node {
  constructor(element) {
    this.element = element;
    this.next = null;
  }
}

class CircularLinkedList {
  constructor() {
    this.head = null
    this.length = 0;
  }

  append(element) {
    const node = new Node(element);
    if (this.head === null) {
      this.head = node;
      // 只有一个的情况下 指向的是head自身
      node.next = this.head;
    } else {
      let currentNode = this.head;
      while(currentNode != this.head) {
        currentNode = currentNode.next
      }
      currentNode.next = node;
      node.next = this.head;
    }
    this.length++;
  }

  insert(position, element) {
    if (position >= 0 && position <= this.length) {
      const node = new Node(element);
      let currentNode = this.head;
      let prevNode = null;
      let index = 0;
      if (position === 0) {
        if (this.head === null) {
          this.head = node;
          node.next = this.head;
        } else {
          while(index < position) {
            prevNode = currentNode;
            currentNode = currentNode.next;
            index++
          }
          prevNode.next = node;
          node.next = currentNode;
        }
      }
      this.length++;
      return true;
    } else {
      return false;
    }
  }

  removeAt(position) {
    if (position > -1 && position < this.length) {
      let currentNode = this.head;
      let prevNode = null;
      let index = 0;
      if (position === 0) {
        this.head = currentNode.next;
      } else {
        while(index < position) {
          prevNode = currentNode;
          currentNode = currentNode.next;
          index++;
        }
        prevNode.next = currentNode.next;
      }
      this.length--;
      return true;
    }
    return false;
  }

  remove(element) {
    const index = this.indexOf(element);
    this.removeAt(element);
  }

  indexOf(element) {
    let currentNode = this.head;
    let index = 0;
    while (currentNode && index < this.length) {
        if (currentNode.element === element) {
            return index;
        } else {
            currentNode = currentNode.next;
            index++;
        }
    }
    return -1;
  }

  isEmpty() {
    return this.length === 0;
  }
}